# -*- coding=utf8 -*-
__author__ = 'nickleo'

from beans.shape import shape, shape_charts, shape_group
import jsonpickle as json
from config import HogWartsConfig as cfg
import http_client as http
import time
from datetime import datetime, timedelta


def all():
    action_alert = ""
    result = []
    for name_server in cfg().get_nameservers():
        http_result = http.get_clusterlist(name_server)
        group = shape_group("nameserver:" + name_server, name_server)
        if http_result is None or http_result.strip() == '':
            result.append(group)
            action_alert = 'nameserver:' + name_server + 'is No Clusters'
        else:
            list = __decode_cluser_list(json.decode(http_result))
            group.shapes = list
            result.append(group)
    return result, action_alert
    # [


# {"OutTotalToday": "65172088",
# "InTotalToday": "60395608",
# "Version": "V3_2_4_SNAPSHOT",
# "InTPS": "1248.6502699460107",
# "ClusterName": "FetionMQCluster",
# "OutTotalYest": "65906823",
# "BID": "0",
# "OutTPS": "1248.6502699460107",
# "InTotalYest": "70536607",
# "BrokerName": "fetionmq",
# "Addr": "192.168.143.130:10911"},
# {"OutTotalToday": "0", "InTotalToday": "61133718", "Version": "V3_2_4_SNAPSHOT", "InTPS": "1270.645870825835",
# "ClusterName": "FetionMQCluster", "OutTotalYest": "0", "BID": "1", "OutTPS": "0.0", "InTotalYest": "69798441",
# "BrokerName": "fetionmq", "Addr": "192.168.143.133:10911"}]


def __decode_cluser_list(result):
    list = []
    for cluster in result:
        shape_tmp = shape(cluster['BID'],
                          'green',
                          'BID:' + cluster['BID'],
                          'In:' + cluster['InTotalToday'] + "\n Out:" + cluster['OutTotalToday'],
                          cluster['ClusterName'])
        shape_tmp._detail = cluster['Addr']

        list.append(shape_tmp)
    return list


def cluster_bid_mapping():
    action_alert = ""
    result = []
    for name_server in cfg().get_nameservers():
        http_result = http.get_clusterlist(name_server)
        if http_result is None or http_result.strip() == '':
            action_alert = 'nameserver:' + name_server + 'is No Clusters '
        else:

            for cluster in json.decode(http_result):
                tmp = {'addr': cluster['Addr'],
                       'bid': cluster['BID'],
                       'clustername': cluster['ClusterName']
                       }
                result.append(tmp)

    return result, action_alert


def __getSecTime(type, value):
    import string

    int_value = string.atoi(value)
    if type == "minute":
        timeValue = 60 * int_value
    elif type == "hour":
        timeValue = 60 * 60 * int_value
    elif type == "day":
        timeValue = 24 * 60 * 60 * int_value
    elif type == "week":
        timeValue = 7 * 24 * 60 * 60 * int_value
    elif type == "month":
        timeValue = 30 * 24 * 60 * 60 * int_value
    else:
        timeValue = -1
    return timeValue


def shapeAreaCharts(clustername, shape_id, time_type, time_time, name_server, datatype):
    action_alert = ""
    result = []
    if time_type == "realtime":
        time_value = 14 * 60
    else:
        time_value = __getSecTime(time_type, time_time)
    if time_value == -1:
        action_alert = "time or type error time_type=" + time_type + " time_time=" + time_time
    else:
        result, action_alert = __getAreaData(clustername, shape_id, time_value, name_server, datatype)

    return result, action_alert


def __getAreaData(clustername, shape_id, time_value, name_server, datatype):
    if datatype == 'total':
        return __getTotalData(clustername, shape_id, time_value, name_server)
    elif datatype == 'tps':
        return __getTPSData(clustername, shape_id, time_value, name_server)


def __getTotalData(cluster_name, bid, time_value, name_server):
    action_alert = ""
    result = []
    nowtime = datetime.now()
    start = nowtime - timedelta(seconds=time_value)
    startTime = start.strftime("%Y-%m-%d %H:%M:%S")
    endTime = nowtime.strftime("%Y-%m-%d %H:%M:%S")
    # print startTime,endTime
    result = {'data': [],
              'xkey': '',
              'ykeys': [],
              'labels': []
              }

    if time_value > ( 7 * 24 * 60 * 60):
        http_result = http.get_brokerTotal(cluster_name, bid, startTime, endTime)
    else:
        http_result = http.get_brokerDetailTotal(cluster_name, bid, startTime, endTime)

    if http_result is None or http_result.strip() == '':
        action_alert = 'clustername:' + cluster_name + ';Bid:' + bid + 'startTime:' + startTime
    else:

        datalist = []
        xkey = 'time'
        ykeys = ['inTotal', 'outTotal']
        labels = ['inTotal', 'outTotal']
        for data in json.decode(http_result):
            #{"brokerId":0,"clusterName":"FetionMQCluster","date":1425806906000,"inTotal":0,"nameServerAddr":"192.168.143.135:9876","outTotal":0}
            temp_data = {
                'time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['date'] / 1000)),
                'inTotal': data['inTotal'],
                'outTotal': data['outTotal'],
            }
            datalist.append(temp_data)

        result['xkey'] = xkey
        result['ykeys'] = ykeys
        result['labels'] = labels
        result['data'] = datalist
    return result, action_alert


def __getTPSData(cluster_name, bid, time_value, name_server):
    action_alert = ""
    result = []
    nowtime = datetime.now()
    start = nowtime - timedelta(seconds=time_value)
    startTime = start.strftime("%Y-%m-%d %H:%M:%S")
    endTime = nowtime.strftime("%Y-%m-%d %H:%M:%S")
    # print startTime,endTime
    result = {'data': [],
              'xkey': '',
              'ykeys': [],
              'labels': []
              }

    http_result = http.get_brokerTps(cluster_name, bid, startTime, endTime)
    print http_result
    if http_result is None or http_result.strip() == '':
        action_alert = 'clustername:' + cluster_name + ';Bid:' + bid + 'startTime:' + startTime
    else:

        datalist = []
        xkey = 'time'
        ykeys = ['inTps', 'outTps']
        labels = ['inTps', 'outTps']

        for data in json.decode(http_result):
            #{"brokerId":0,"clusterName":"FetionMQCluster","date":1425806906000,"inTotal":0,"nameServerAddr":"192.168.143.135:9876","outTotal":0}
            temp_data = {
                'time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['date'] / 1000)),
                'inTps': data['inTps'],
                'outTps': data['outTps'],
            }
            datalist.append(temp_data)

        result['xkey'] = xkey
        result['ykeys'] = ykeys
        result['labels'] = labels
        result['data'] = datalist
    return result, action_alert


def shapeCharts(cluster_name, bid, query_time):
    time_src = time.strptime(query_time, '%Y-%m');
    start = datetime(*time_src[:6])
    from dateutil.relativedelta import *

    end = start + relativedelta(months=1)
    startTime = start.strftime("%Y-%m-%d %H:%M:%S")
    endTime = end.strftime("%Y-%m-%d %H:%M:%S")
    # print startTime,endTime
    result = shape_charts()
    result.set_xAxis_all({'type': 'datetime', 'dateTimeLabelFormats': "{   day: '%e. %b' }"})
    result.set_chart_type('spline')
    result.set_tooltip({
        'valueSuffix': ' Total'
    })

    result.set_title('Cluster:' + cluster_name + '.Bid(' + bid + ') Total  ')

    dataarrs = [];
    http_result = http.get_brokerTotal(cluster_name, bid, startTime, endTime)
    if http_result is None or http_result.strip() == '':
        action_alert = 'clustername:' + cluster_name + ';Bid:' + bid + 'query_time:' + query_time
    else:

        tmp_in_list = []
        tmp_out_list = []
        for data in json.decode(http_result):
            #{"brokerId":0,"clusterName":"FetionMQCluster","date":1425806906000,"inTotal":0,"nameServerAddr":"192.168.143.135:9876","outTotal":0}
            tmp_in_one_data = [
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['date'] / 1000)), data['inTotal']
            ]
            tmp_in_list.append(tmp_in_one_data)
            tmp_out_one_data = [
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['date'] / 1000)), data['outTotal']
            ]
            tmp_out_list.append(tmp_out_one_data)

        in_temp_data = {'name': 'inTotal',
                        'data': tmp_in_list
                        }
        out_temp_data = {'name': 'outTotal',
                         'data': tmp_out_list
                         }
        dataarrs.append(in_temp_data)
        dataarrs.append(out_temp_data)
        result.set_series_all(dataarrs)
    return result;


##-----⬇-----DEMO-----⬇-----DEMO----⬇️------DEMO-----⬇----DEMO-----⬇----DEMO------⬇----DEMO------⬇------------
def allDemo():
    list = []
    # green,red,yellow

    list.append(shape(2222, 'green', 'queue 2 test', 9999))
    list.append(shape(3333, 'green', 'queue 3 test', 55445))
    list.append(shape(4444, 'green', 'queue 4 test', 123))
    list.append(shape(7777, 'red', 'queue 6 test', 111111))

    list1 = []
    list1.append(shape(1111, 'red', 'queue 1 test', 1000000))
    list1.append(shape(3333, 'red', 'queue 3 test', 55445))
    list1.append(shape(5555, 'red', 'queue 5 test', 32444))
    list1.append(shape(6666, 'red', 'queue 6 test', 1234))
    list1.append(shape(7777, 'green', 'queue 6 test', 111111))
    list1.append(shape(7777, 'red', 'queue 6 test', 111111))
    list1.append(shape(7777, 'red', 'queue 6 test', 111111))

    result = []
    result.append(shape_group("分组111111111", list))
    result.append(shape_group("分组999999999999", list1))

    return result;


def shapeChartsDemo():
    result = shape_charts()
    start = time.time() - 86400 * 30;
    # days = [time.strftime('%m/%d',time.localtime(day*86400*2 + start)) for day in range(15)]
    # result.set_xAxis(days)


    result.set_xAxis_all({'type': 'datetime', 'dateTimeLabelFormats': "{   day: '%e. %b' }"})
    result.set_chart_type('spline')
    result.set_tooltip({
        'valueSuffix': ' TPS'
    })
    dataarrs = [];
    import random

    for i in range(3):
        tmp = {
            'name': 'topic : ' + str(i),
            # [Date.UTC(1971,  5, 12), 0   ]
            'data': [[time.strftime('%y-%m-%d', time.localtime(i * 86400 + start)), random.randint(10, 20)] for i in
                     range(31)]
        }
        dataarrs.append(tmp)
    result.set_series_all(dataarrs)
    return result


print time.timezone
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1425984187))